const express = require('express'),
  router = express.Router(),   
  util = require("../util/util"),
  payment = require("../model/payment"),
  book = require("../model/book"),
  statistic = require("../model/statistic"),
  dayjs = require('dayjs'),
  reObj = util.reObj;
  //import dayjs from 'dayjs' // ES 2015
  

/**
 * @function 添加支付信息
 * @author Eric
 * @date 2018-08-01
 * @param name,code,addr,area,status
 */
router.post('/addpv', async (req, res) => {
    let day=dayjs().format("YYYY-MM-DD")    
    req.body.pv=1
    req.body.type=0
    //console.log(req.ip.match(/d+.d+.d+.d+/)+"ssss")
    req.body.userip=req.ip.split("f:")[1]
    try {
      let bookid=req.body.bookid
      
      let bookRecord=await book.findOne({where: {id:bookid}})
      
      req.body.bookname=bookRecord.name
      req.body.author=bookRecord.author
      let paymentRecord=await payment.create(req.body)
      req.body.date=day
      let statisticRecord=await statistic.findOrCreate({where: {date:day,bookid:req.body.bookid},defaults:req.body})
      console.log("statisticRecord:"+JSON.stringify(statisticRecord))
      
      
      let averageratio=(parseInt(statisticRecord[0].paymentcount)/(statisticRecord[0].pvtotal>0?parseInt(statisticRecord[0].pvtotal):1)).toFixed(2)
      
      if(parseInt(statisticRecord[0].pvtotal)===0)
      {
        averageratio=0
      } 
      let updateObj={
        
        //amounttotal:parseInt(statisticRecord[0].amounttotal)+parseInt(statisticRecord[0].price),
        pvtotal:parseInt(statisticRecord[0].pvtotal)+1,
        averageratio:averageratio
      }
      console.log("statisticRecord:"+JSON.stringify(statisticRecord))
      
      await statistic.update(updateObj, {where: {date:day,bookid:bookid}})
      res.send(reObj(0, '添加成功', paymentRecord))
    } catch (error) {      
      console.log("error:"+JSON.stringify(error))
      res.send(reObj(-1, '添加失败', error))
    }
    

})
router.post('/addpayment', async (req, res) => {
  /* req.body.userip=req.ip.split("f:")[1]
    payment.create(        
        req.body
    ).then(record => {      
        if (record) {
            res.send(reObj(0, '添加成功', record[0]))
        }
    }).catch(err => {
        res.send(reObj(-1, '添加失败', err))
    }); */
    let day=dayjs().format("YYYY-MM-DD")    
    
    req.body.userip=req.ip.split("f:")[1]
    try {
      let bookid=req.body.bookid
      
      let bookRecord=await book.findOne({where: {id:bookid}})
      
      req.body.bookname=bookRecord.name
      let paymentRecord=await payment.create(req.body)
      req.body.date=day
      let statisticRecord=await statistic.findOrCreate({where: {date:day,bookid:bookid},defaults:req.body})
      let averageratio=(parseInt(statisticRecord[0].paymentcount)/(statisticRecord[0].pvtotal>0?parseInt(statisticRecord[0].pvtotal):1)).toFixed(2)
      if(parseInt(statisticRecord[0].pvtotal)===0)
      {
        averageratio=0
      }      
      console.log("averageratio:"+averageratio)
      let updateObj={
        price:req.body.price,
        amounttotal:parseFloat(statisticRecord[0].amounttotal)+parseFloat(req.body.price),
        paymentcount:parseInt(statisticRecord[0].paymentcount)+1,
        averageratio:averageratio
      }
      
     // let statisticRecord=await statistic.findOne({where: {date:day,id:bookid}})
      
      await statistic.update(updateObj, {where: {date:day,bookid:bookid}})
      res.send(reObj(0, '添加成功', paymentRecord))
    } catch (error) {      
      console.log("error:"+JSON.stringify(error))
      res.send(reObj(-1, '添加失败', error))
    }

})
/**
 * @function 编辑支付信息
 * @author Eric
 * @date 2018-08-01
 * @param id,name,code,addr,area,status
 */
router.post('/update', (req, res) => {
  let id = req.body.id
  let params = {
    id: id
  }

    payment.update(req.body, {where: params}).then(record => {
        if (record[0] > 0) {
            console.log("record:"+JSON.stringify(record))
            res.send(reObj(0, '修改成功', record[0]))
        } else {
            res.send(reObj(-1, '无效的id', []))
        }
    }).catch(err => {
        res.send(reObj(-1, '修改失败', err))
    });

})

/**
 * @function 删除信息
 * @author Eric
 * @date 2018-07-31
 * @param id
 */
router.post('/del', (req, res) => {
  let params = {
    id: req.body.id
  }

  payment.destroy({where: params}).then(record => {
    if (record > 0) {
      res.send(reObj(0, '删除会议成功', record))
    } else {
      res.send(reObj(-1, '删除会议失败或此记录不存在', record))
    }
  }).catch(err => {
    res.send(reObj(-1, '删除会议失败', err))
  });
})

/**
 * @function 获取单个信息
 * @author Eric
 * @date 2018-08-01
 * @param meetingid
 */
router.post('/findone', (req, res) => {
  let params = {}
  let id = req.body.id
  if (id) {
    params.id = id;

    payment.findOne({where: params}).then(record => {
      if (record) {
        res.send(reObj(0, '获取信息成功', record))
      } else {
        res.send(reObj(-1, '获取信息失败或此记录不存在', {}))
      }
    }).catch(err => {
      res.send(reObj(-1, '获取信息失败', err))
    });
  } else {
    res.send(reObj(-1, 'id不能为空', []))
  }
})


/**
 * @function 获取所有数据(支持分页，条件过滤)
 * @author Eric
 * @date 2018-07-31
 * @param page,pagerow,meetingname,meetingtype
 */

router.post('/findall', (req, res) => {
  /* let meetingname = req.body.meetingname || ''
   let meetingtype = req.body.meetingtype || ''*/
   let params = req.body
   let pagerow = parseInt(req.body.pagerow)
   let page = parseInt(req.body.page)
   if(pagerow){
     delete params.pagerow;
   }
   if(page){
     delete params.page;
   }
   //对页码进行容错
   if (pagerow > 999) {
     pagerow = 999
   }
   if (page == 0) {
     page = 1
   }
 
   //筛选条件
 /*  if (meetingname) {
     params.meetingname = {'$like': '%' + meetingname + '%'}
   }
   if (meetingtype) {
     params.meetingtype = meetingtype
   }*/
   if(req.body.startDate&&req.body.endDate)
   {
    params.creattime={$between: [dayjs(req.body.startDate).format(), dayjs(req.body.endDate).format()]}
   }
   console.log("params:"+JSON.stringify(params))
   delete params["startDate"]
   delete params["endDate"]
   
   

   payment.findAndCountAll({
     order: "creattime DESC",
     limit: pagerow || 100,
     offset: parseInt(pagerow * (page - 1)) || 0,
     where: params
   }).then(record => {
     if(record.count>0){
       res.send(reObj(0, '获取数据成功', record.rows, record.count))
     }
     else
     {
       res.send(reObj(0, '没有符合条件的记录', record.rows, record.count))
     }
     
   }).catch(err => {
     console.log("err:"+JSON.stringify(err))
     res.send(reObj(-1, '获取数据失败', err))
   });
 })
 


module.exports = router;
